<template>
  <main>
    <section class="login">
      <h1>Login</h1>
      <Form :label-width="73" label-position="top">
        <FormItem label="username">
          <Input 
            v-model.trim="username" 
            @keyup.enter.native="beforeSubmit" 
            placeholder="Enter username..."
          />
        </FormItem>
        <FormItem label="password">
          <Input
            v-model.trim="password"
            @keyup.enter.native="beforeSubmit"
            type="password"
            placeholder="Enter password..."
          />
        </FormItem>
        <FormItem class="my-button">
          <Button type="primary" @click="beforeSubmit">Submit</Button>
          <Button style="margin-top: 20px" @click="back">Cancel</Button>
        </FormItem>
      </Form>
    </section>
  </main>
</template>

<script>
import { profileLogin } from 'service'
import { loading } from 'mixins/loading'

export default {
  name: 'Login',
  mixins: [loading],
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    beforeSubmit() {
      if (this.username === '') {
        this.$Message.warning('Please enter your username')
      } else if (this.password === '') {
        this.$Message.warning('Please enter your password')
      } else {
        this.openLoading('Loading~~')
        this.submit(this.username, this.password)
      }
    },
    async submit(username, password) {
      let res = await profileLogin(username, password)
      if (!res.data.flag) {
        this.$Message.warning(res.data.errorMsg)
      } else {
        window.localStorage["token"] = res.data.token;
        this.$store.dispatch('user/SETUSER', res.data.data)
        if (this.$route.query && this.$route.query.returnUrl) {
          window.location.href = this.$route.query.returnUrl
        } else {
          this.$router.push({ name: 'profile'})
        }
      }
      this.$Spin.hide()
    },
    back() {
      this.$router.push('/')
    }
  },
}
</script>

<style lang='scss' scoped>
section {
  padding: 40px 50px 28px;
  animation: main 0.5s linear;
  h1 {
    text-align: center;
    color: #28cfcf;
    text-shadow: 2px 2px 3px #adadad;
    font-size: 42px;
  }
  .ivu-form {
    width: 300px;
    margin: 40px auto 0;
  }
}
</style>
<style lang="scss">
.login {
  .ivu-form {
    .ivu-form-item-label {
      font-size: 14px;
      text-align: left;
    }
    .ivu-form-item-content {
      margin-left: 0 !important;
    }
    input {
      font-size: 14px;
    }
    .my-button {
      margin-top: 60px;
      .ivu-form-item-content {
        text-align: center;

        button {
          width: 100%;
        }
      }
    }
  }
}
</style>
